# -*- coding: cp1251  -*-

from numpy import *
from fractions import Fraction
from TeXManipulations import *

NF = -10000000 # not found

def LoadMatrix():
    f = open("Matrix.txt")
    lines = f.readlines()
    res = array(map(lambda s: map(Fraction, s.split()), lines))
    return res

def FindFirstNonZero(A):
    for i in xrange(len(A)):
        if A[i] != 0:
            return i
    return NF

def IsMatrixZero(A):
    if FindFirstNonZero(A) < 0:
    	return 0
    else:
    	return 1
    
def SwapRows(A, i, j):
    if i != j:
	WriteLTex("Поміняємо місцями $", i+1, "$-ий та $", j+1, "$-ий рядки:")  
        A[i], A[j] = A[j].copy(), A[i].copy()

def ReduceColumnElement(A,icolumn,irow,i):
    k = A[i][icolumn]/A[irow][icolumn]
    if k > 0:                                                                                                  
	WriteTex("Віднімемо від $", i+1, "$-го рядка $", irow+1, "$-ий помножений на $") 
	WriteNumTex(k)
	WriteLTex('$:')
	A[i] = A[i] - k*A[irow]                                                                                 
#	WriteTex('$'+'\\tilde'+'$ ')                          
	WriteMatrix(A)
	WriteLTex(' ')
    elif k != 0:                                                                                            
	WriteTex('Додамо до $', i+1, '$-го рядка $', irow+1, '$-ий помножений на $')
	WriteNumTex(-k)
	WriteLTex('$:')
	A[i] = A[i] - k*A[irow]                                                                                 
#	WriteTex('$'+'\\tilde'+'$ ')                          
	WriteMatrix(A)
	WriteLTex()
    return A

def ReduceToTriangular(A): 
    nrow, ncolumn = len(A), len(A[0])
    ncol = min(ncolumn,nrow)
    irow = icolumn = 0
    while irow < nrow and icolumn < ncol:
        i = FindFirstNonZero(A[irow:, icolumn]) + irow
        if i < 0: # non-zero element not found
            icolumn += 1
            continue
	if i > irow:
            SwapRows(A, irow, i)
#	    WriteTex('$'+'\\tilde'+'$ ')                          
	    WriteMatrix(A)
	    WriteLTex()
        for i in xrange(irow+1, nrow):
	    ReduceColumnElement(A, icolumn, irow, i)
        irow += 1
        icolumn += 1
    return A

def ReduceTriangularToDiagonal(A):
    irow = len(A)-1
    while irow > 0:
        if IsMatrixZero(A[irow]):
    	    continue
    	irow -= 1
    ncol = irow
    for icolumn in xrange(ncol, 0, -1):
    	irow = icolumn
        for i in xrange(irow-1, -1, -1):
	    ReduceColumnElement(A, icolumn, irow, i)


#def TransposedMAtrix(A):
#    nrow, ncolumn = len(A), len(A[0])
#    for i in range(nrow):
#    	for j in range(i,ncolumn)

